//
//  GlobalFile.m
//  EraPig
//
//  Created by Mac_Mini on 2021/1/7.
//

#import "GlobalFile.h"
#import <SVProgressHUD.h>
@implementation GlobalFile

/*=============================app内颜色=============================*/
/**
 主题颜色#FE504F
 
 @return UIColor
 */
+ (UIColor *)themeColor{
    return [GlobalFile colorWithRed:254 green:80 blue:79 alpha:1.0];
}

/**
 view背景颜色
 
 @return UIColor
 */
+ (UIColor *)backgroundColor{
    return [GlobalFile colorWithRed:255 green:248 blue:248 alpha:1.0];
}

/**
 企业团餐主题颜色#578BFF
 
 @return UIColor
 */
+ (UIColor *)themeColorForCGM{
    return [GlobalFile colorWithRed:87 green:139 blue:255 alpha:1.0];
}

/**
 企业团餐view背景颜色
 
 @return UIColor
 */
+ (UIColor *)backgroundColorForCGM{
    return [GlobalFile colorWithRed:242 green:245 blue:255 alpha:1.0];
}

/**
 颜色
 */
+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha {
    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha];
}

/*=============================app内字体大小和字体颜色=============================*/

/**
 字体：8
 
 @return UIFont
 */
+ (UIFont *)fontOfSize8 {
    return [UIFont systemFontOfSize:8.0f];
}

/**
 字体：9
 
 @return UIFont
 */
+ (UIFont *)fontOfSize9 {
    return [UIFont systemFontOfSize:9.0f];
}

/**
 字体：10
 
 @return UIFont
 */
+ (UIFont *)fontOfSize10 {
    return [UIFont systemFontOfSize:10.0f];
}

/**
 字体：11
 
 @return UIFont
 */
+ (UIFont *)fontOfSize11 {
    return [UIFont systemFontOfSize:11.0f];
}

/**
 字体：12
 
 @return UIFont
 */
+ (UIFont *)fontOfSize12 {
    return [UIFont systemFontOfSize:12.0f];
}

/**
 字体：13
 
 @return UIFont
 */
+ (UIFont *)fontOfSize13 {
    return [UIFont systemFontOfSize:13.0f];
}

/**
 字体：14
 
 @return UIFont
 */
+ (UIFont *)fontOfSize14 {
    return [UIFont systemFontOfSize:14.0f];
}

/**
 字体：15
 
 @return UIFont
 */
+ (UIFont *)fontOfSize15 {
    return [UIFont systemFontOfSize:15.0f];
}

/**
 字体：16
 
 @return UIFont
 */
+ (UIFont *)fontOfSize16 {
    return [UIFont systemFontOfSize:16.0f];
}

/**
 字体：17
 
 @return UIFont
 */
+ (UIFont *)fontOfSize17 {
    return [UIFont systemFontOfSize:17.0f];
}

/**
 字体：18
 
 @return UIFont
 */
+ (UIFont *)fontOfSize18 {
    return [UIFont systemFontOfSize:18.0f];
}

/**
 字体：20
 
 @return UIFont
 */
+ (UIFont *)fontOfSize20 {
    return [UIFont systemFontOfSize:20.0f];
}

/**
 字体：22
 
 @return UIFont
 */
+ (UIFont *)fontOfSize22 {
    return [UIFont systemFontOfSize:22.0f];
}

/**
 字体：24
 
 @return UIFont
 */
+ (UIFont *)fontOfSize24 {
    return [UIFont systemFontOfSize:24.0f];
}

/**
 字号：8
 
 @return CGFloat
 */
+ (CGFloat)fontSize8 {
    return 8.0f;
}

/**
 字号：9
 
 @return CGFloat
 */
+ (CGFloat)fontSize9 {
    return 9.0f;
}

/**
 字号：10
 
 @return CGFloat
 */
+ (CGFloat)fontSize10 {
    return 10.0f;
}

/**
 字号：11
 
 @return CGFloat
 */
+ (CGFloat)fontSize11 {
    return 11.0f;
}

/**
 字号：12
 
 @return CGFloat
 */
+ (CGFloat)fontSize12 {
    return 12.0f;
}

/**
 字号：13
 
 @return CGFloat
 */
+ (CGFloat)fontSize13 {
    return 13.0f;
}

/**
 字号：14
 
 @return CGFloat
 */
+ (CGFloat)fontSize14 {
    return 14.0f;
}

/**
 字号：15
 
 @return CGFloat
 */
+ (CGFloat)fontSize15 {
    return 15.0f;
}

/**
 字号：16
 
 @return CGFloat
 */
+ (CGFloat)fontSize16 {
    return 16.0f;
}

/**
 字号：17
 
 @return CGFloat
 */
+ (CGFloat)fontSize17 {
    return 17.0f;
}

/**
 字号：18
 
 @return CGFloat
 */
+ (CGFloat)fontSize18 {
    return 18.0f;
}

/**
 字号：20
 
 @return CGFloat
 */
+ (CGFloat)fontSize20 {
    return 20.0f;
}

/**
 字号：22
 
 @return CGFloat
 */
+ (CGFloat)fontSize22 {
    return 22.0f;
}

/**
 字号：24
 
 @return CGFloat
 */
+ (CGFloat)fontSize24 {
    return 24.0f;
}

/**
 字体颜色：主题色
 
 @return UIColor
 */
+ (UIColor *)textColorWithTheme {
    return [self themeColor];
}

/**
 字体颜色：白色
 
 @return UIColor
 */
+ (UIColor *)textColorWithWhite {
    return [UIColor whiteColor];
}

/**
 字体颜色：默认深黑色
 
 @return UIColor
 */
+ (UIColor *)textColorWithDefaultBlack {
    return [GlobalFile colorWithRed:61.0 green:61.0 blue:61.0 alpha:1.0f];
}

/**
 字体颜色：默认浅黑色
 
 @return UIColor
 */
+ (UIColor *)textColorWithDefaultLightBlack {
    return [GlobalFile colorWithRed:87.0 green:87.0 blue:87.0 alpha:1.0f];
}

/**
 字体颜色：灰色
 
 @return UIColor
 */
+ (UIColor *)textColorWithGrey {
    return [UIColor grayColor];
}

/**
 字体颜色:浅灰色
 
 @return UIColor
 */
+ (UIColor *)textColorWithLightGreyColor {
    return [GlobalFile colorWithRed:204.0 green:204.0 blue:204.0 alpha:1];
}

/**
 placeholder颜色
 
 @return placeholder颜色
 */
+ (UIColor *)textPlaceholderLightGreyColor {
    return [GlobalFile colorWithRed:184.0 green:184.0 blue:184.0 alpha:1.0f];
}
/*=============================网络提示语=============================*/
+ (NSString *)networkFailure{
    return @"网络异常";
}
/*=============================app信息=============================*/
+ (NSString *)appName{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleDisplayName"];;
}

/*=============================图片处理=============================*/
/**
 自定义颜色image
 
 @return UIImage
 */
+ (UIImage *)imageWithColor:(UIColor *)color{
    return [GlobalFile imageWithColor:color size:CGSizeMake(10, 10)];
}
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0, 0, size.width, size.height); // 图片尺寸
    UIGraphicsBeginImageContext(rect.size); // 填充画笔
    CGContextRef context = UIGraphicsGetCurrentContext(); // 根据所传颜色绘制
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect); // 联系显示区域
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); // 得到图片信息
    UIGraphicsEndImageContext(); // 消除画笔
    return image;
}

/*=============================其他=============================*/
/**
 价格保留小数Float
 
 @param tfloat 的价格
 @param count  价格的小数点位数（最多两位小数）
 @return NSString
 */
+ (NSString *)stringFromeFloat:(CGFloat)tfloat decimalPlacesCount:(NSInteger)count {
    if (count == 0) { // 没有小数点
        return [NSString stringWithFormat:@"%.0f", tfloat];
    } else if (count == 1) { // 一位小数点
        return [NSString stringWithFormat:@"%.1f", tfloat];
    } else { // 两位小数点
        return [NSString stringWithFormat:@"%.2f", tfloat];
    }
}
/**
 价格保留小数Double
 
 @param tdouble 的价格
 @param count  价格的小数点位数（最多两位小数）
 @return NSString
 */
+ (NSString *)stringFromeDouble:(double)tdouble decimalPlacesCount:(NSInteger)count {
    if (count == 0) { // 没有小数点
        return [NSString stringWithFormat:@"%.0f", tdouble];
    } else if (count == 1) { // 一位小数点
        return [NSString stringWithFormat:@"%.1f", tdouble];
    } else { // 两位小数点
        return [NSString stringWithFormat:@"%.2f", tdouble];
    }
}
/**
 格式化小数  删除末位的0
 
 @param decimal 小数
 @param count  小数点位数
 @return NSString
 */
+ (NSString *)formatterDecimal:(CGFloat)decimal decimalPlacesCount:(NSInteger)count{
    NSString *tempStr = [NSString stringWithFormat:@"%f",decimal];
    NSRange decimalRange = [tempStr rangeOfString:@"."];
    if (decimalRange.length == 0) {
        return tempStr;
    }
    if (count<tempStr.length-NSMaxRange(decimalRange)) {
        //第一次循环 将字符串格式化到count满足的位数
        while (count<tempStr.length-NSMaxRange(decimalRange)) {
            tempStr = [tempStr substringToIndex:tempStr.length-1];
        }
    }
    //第二次循环 将字符串末尾的0删除
    while ([[tempStr substringFromIndex:tempStr.length-1] isEqualToString:@"0"]) {
        tempStr = [tempStr substringToIndex:tempStr.length-1];
    }
    //如果末位是小数点 删除
    if ([[tempStr substringFromIndex:tempStr.length-1] isEqualToString:@"."]) {
        tempStr = [tempStr substringToIndex:tempStr.length-1];
    }
    return tempStr;
}


+ (UIImage *)defaultHeader{
    return kImageNamed(@"icon_default_header");
}

/// 获取网络图片高度
+ (CGSize)getImageSizeWithURL:(id)URL{
    NSURL * url = nil;
    if ([URL isKindOfClass:[NSURL class]]) {
        url = URL;
    }
    if ([URL isKindOfClass:[NSString class]]) {
        url = [NSURL URLWithString:URL];
    }
    if (!URL) {
        return CGSizeZero;
    }
    CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    CGFloat width = 0, height = 0;
    
    if (imageSourceRef) {
        
        // 获取图像属性
        CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);
        
        //以下是对手机32位、64位的处理
        if (imageProperties != NULL) {
            
            CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
            
    #if defined(__LP64__) && __LP64__
            if (widthNumberRef != NULL) {
                CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);
            }
            
            CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
            
            if (heightNumberRef != NULL) {
                CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
            }
    #else
            if (widthNumberRef != NULL) {
                CFNumberGetValue(widthNumberRef, kCFNumberFloat32Type, &width);
            }
            
            CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
            
            if (heightNumberRef != NULL) {
                CFNumberGetValue(heightNumberRef, kCFNumberFloat32Type, &height);
            }
    #endif
            /***************** 此处解决返回图片宽高相反问题 *****************/
            // 图像旋转的方向属性
            NSInteger orientation = [(__bridge NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyOrientation) integerValue];
            CGFloat temp = 0;
            switch (orientation) {  // 如果图像的方向不是正的，则宽高互换
                case UIImageOrientationLeft: // 向左逆时针旋转90度
                case UIImageOrientationRight: // 向右顺时针旋转90度
                case UIImageOrientationLeftMirrored: // 在水平翻转之后向左逆时针旋转90度
                case UIImageOrientationRightMirrored: { // 在水平翻转之后向右顺时针旋转90度
                    temp = width;
                    width = height;
                    height = temp;
                }
                    break;
                default:
                    break;
            }
            /***************** 此处解决返回图片宽高相反问题 *****************/
            
            CFRelease(imageProperties);
        }
        CFRelease(imageSourceRef);
    }

    return CGSizeMake(width, height);
}

/**
 时间戳转换
 假设当前时间是 2021-03-30 10:30
 2021-03-29 10:30 -> "昨天10:30"
 2021-03-30 10:30 -> "今天10:30"
 2021-03-31 10:30 -> "明天10:30"
 */
+ (NSString *)timestampToChinese:(double)timestamp{
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    if ([calendar isDateInYesterday:date]) {
        formatter.dateFormat = @"昨天HH:mm";
    }else if ([calendar isDateInToday:date]){
        formatter.dateFormat = @"今天HH:mm";
    }else if ([calendar isDateInTomorrow:date]){
        formatter.dateFormat = @"明天HH:mm";
    }else{
        formatter.dateFormat = @"MM-dd HH:mm";
    }
    
    return [formatter stringFromDate:date];
}

/// 时间戳转date
/// @param timestamp 时间戳
+ (NSDate *)timestampToDate:(double)timestamp{
    return [NSDate dateWithTimeIntervalSince1970:timestamp];
}

/*
iOS 10拨打系统电话发现弹出框会延迟2s左右出现，很不爽，研究了一下，发现是openURL在iOS 10及其之后会阻塞主线程

所以，拨打电话前，做个判断，来代码,
*/
// 拨打电话
+ (void)callPhone:(NSString *)phoneNumber {
    if (phoneNumber.length == 0) {
        return;
    }
    
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", phoneNumber];
    // 解决iOS10及其以上系统弹出拨号框延迟的问题
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}


/// 截屏
/// @param view 截取的view
+ (UIImage *)screenshotByView:(UIView *)view{
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
//    UIGraphicsBeginImageContext(view.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

/// 保存图片到相册
/// @param image 要保存的图片
+ (void)saveImageToAlbum:(UIImage *)image{
    UIImageWriteToSavedPhotosAlbum(image, [self new], @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存失败!" ;
    }else{
        msg = @"保存成功!" ;
    }
    [SVProgressHUD showSuccessWithStatus:msg];
}

/**
 *  压缩图片
 *
 *  @param image       需要压缩的图片
 *  @param fImageBytes 希望压缩后的大小(以KB为单位)
 *
 */
+ (void)compressedImageFiles:(UIImage *)image
              imageBytes:(CGFloat)fImageBytes
                  imageBlock:(void(^)(UIImage *image))block
{
    __block UIImage *imageCope = image;
    fImageBytes = fImageBytes * 1024;

    __block NSData *uploadImageData = nil;

    uploadImageData = UIImagePNGRepresentation(imageCope);
    CGSize size = imageCope.size;
    CGFloat imageWidth = size.width;
    CGFloat imageHeight = size.height;

    if (uploadImageData.length > fImageBytes) {
    
        dispatch_async(dispatch_queue_create("CompressedImage", DISPATCH_QUEUE_SERIAL), ^{
        
            CGFloat fBytes = fImageBytes/uploadImageData.length;
        
            CGFloat fScaleArea = imageWidth * imageHeight * fBytes;
        
            CGFloat fImageScale = 0.0;
        
            CGFloat dHeight = 0.0;
        
            CGFloat dWidth = 0.0;
        
            if (imageWidth > imageHeight) {
            
                fImageScale = imageWidth/imageHeight;
                dHeight = sqrtf(fScaleArea/fImageScale);
                dWidth  = dHeight * fImageScale;
            }
            else if (imageHeight > imageWidth) {
            
                fImageScale = imageHeight/imageWidth;
                dWidth = sqrtf(fScaleArea/fImageScale);
                dHeight  = dWidth * fImageScale;
            }
            else {
            
                dWidth = sqrtf(fScaleArea);
                dHeight = dWidth;
            }
        
            UIGraphicsBeginImageContext(CGSizeMake(dWidth, dHeight));
            [imageCope drawInRect:CGRectMake(0, 0, dWidth, dHeight)];
            imageCope = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        
            uploadImageData = UIImagePNGRepresentation(imageCope);
        
            if (uploadImageData.length > fImageBytes) {
                uploadImageData = UIImageJPEGRepresentation(imageCope, 1);
            }
            NSLog(@"图片已经压缩成 %luKB",uploadImageData.length/1024);
            imageCope = [[UIImage alloc] initWithData:uploadImageData];
        
            dispatch_sync(dispatch_get_main_queue(), ^{
                block(imageCope);
            });
        });
    }
    else
    {
        block(imageCope);
    }
}
@end
